package controllers

import (
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"mishop/entitys"
	"mishop/models"
	"mishop/services"
	"mishop/utils"
	"strconv"
)

type ICart interface {
	All(ctx *gin.Context)
	Store(ctx *gin.Context)
	Update(ctx *gin.Context)
	Delete(ctx *gin.Context)
}
type Cart struct {
	service services.ICartService
}

func NewCart() ICart {
	service := services.NewCartService(models.NewCart(models.Db))
	return &Cart{service: service}
}

func (c *Cart) Store(ctx *gin.Context) {
	cartEntity := models.Cart{}
	err := ctx.ShouldBindWith(&cartEntity, binding.JSON)
	utils.HandleErrors(err, ctx, 400, 1, "")
	if err != nil {
		return
	}
	cart, err := c.service.Create(&cartEntity)
	utils.HandleErrors(err, ctx, 400, 1, "")
	if err != nil {
		return
	}
	utils.HandleSucess(ctx, 201, 0, "", cart)

}

func (c *Cart) Update(ctx *gin.Context) {
	cart_id := ctx.Param("cart_id")
	cartID, err := strconv.Atoi(cart_id)
	utils.HandleErrors(err, ctx, 400, 1, "")

	cartEntity := models.Cart{}
	err = ctx.ShouldBindWith(&cartEntity, binding.JSON)
	utils.HandleErrors(err, ctx, 400, 1, "")
	if err != nil {
		return
	}
	cartEntity.ID = uint(cartID)

	cart, err := c.service.Update(&cartEntity)
	utils.HandleErrors(err, ctx, 400, 1, "")
	if err != nil {
		return
	}
	utils.HandleSucess(ctx, 201, 0, "", cart)
}

func (c *Cart) Delete(ctx *gin.Context) {
	cart_id := ctx.Param("cart_id")
	cartID, err := strconv.Atoi(cart_id)
	utils.HandleErrors(err, ctx, 400, 1, "")
	if err != nil {
		return
	}
	err = c.service.Delete(cartID)
	utils.HandleErrors(err, ctx, 400, 1, "")
	if err != nil {
		return
	}
	utils.HandleSucess(ctx, 200, 0, "删除成功", nil)

}

func (c *Cart) All(ctx *gin.Context) {
	pageEntity := entitys.PageEntity{}
	err := ctx.ShouldBindWith(&pageEntity, binding.JSON)
	utils.HandleErrors(err, ctx, 400, 1, "")
	if err != nil {
		return
	}

	userID := 0
	user_id := ctx.Query("user_id")
	if user_id != "" {
		parseInt, err := strconv.Atoi(user_id)
		utils.HandleErrors(err, ctx, 400, 1, "")
		if err != nil {
			return
		}
		userID = parseInt
	}
	pages, err := c.service.FindByUserID(pageEntity.Page,pageEntity.Rows, uint(userID))
	utils.HandleErrors(err, ctx, 400, 1, "")
	if err != nil {
		return
	}
	utils.HandleSucess(ctx, 200, 0, "", pages)
}
